package net.neptech.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.neptech.api.SystemApi;
import net.neptech.dto.sys.StaffDTO;
import net.neptech.enums.workflow.NodeUserTypeEnum;
import net.neptech.model.dto.NodeUser;
import net.neptech.model.sys.Dept;
import net.neptech.model.sys.Role;
import net.neptech.model.vo.OrgDataVo;
import net.neptech.model.vo.OrgSelectShowVo;
import net.neptech.service.OrgService;
import net.neptech.service.WorkflowService;
import net.neptech.util.DataUtil;
import net.neptech.util.DeptUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author Saya
 * @Date 2025/8/24 23:36
 * @Description TODO
 **/
@Service
@Slf4j
@RequiredArgsConstructor
public class OrgServiceImpl implements OrgService {
    private final SystemApi systemApi;
    private final WorkflowService workflowService;
    /**
     * 查询组织架构树
     *
     * @param deptId    部门id
     * @param type      只查询部门架构
     * @param showLeave 是否显示离职员工
     * @return 组织架构树数据
     */
    @Override
    public OrgSelectShowVo getOrgTreeData(String deptId, String type, Boolean showLeave) {

        if (StrUtil.equals(type, NodeUserTypeEnum.ROLE.getKey())) {
            //角色

            List<Role> roleList = systemApi.getAllRole().getData();

            List<OrgDataVo> orgs = new LinkedList<>();

            for (Role role : roleList) {
                OrgDataVo orgTreeDataVo = new OrgDataVo();
                orgTreeDataVo.setId(role.getRoleId().toString());
                orgTreeDataVo.setName(role.getRoleName());
                orgTreeDataVo.setType(NodeUserTypeEnum.ROLE.getKey());
                orgTreeDataVo.setSelected(false);
                orgs.add(orgTreeDataVo);
            }
            return new OrgSelectShowVo(new ArrayList<>(),orgs,orgs,new ArrayList<>());
        }
        OrgSelectShowVo orgSelectShowVo = new OrgSelectShowVo(new ArrayList<>(),new ArrayList<>(),new ArrayList<>(),new ArrayList<>());
        List<Dept> deptList = systemApi.getAllDept().getData();

        //查询所有部门及员工
        {
            List<OrgDataVo> deptVoList = new ArrayList();
            for (Dept dept : deptList) {
                OrgDataVo orgTreeDataVo = new OrgDataVo();
                orgTreeDataVo.setId(dept.getDeptId().toString());
                orgTreeDataVo.setName(dept.getDeptName());
                orgTreeDataVo.setType(NodeUserTypeEnum.DEPT.getKey());
                orgTreeDataVo.setSelected(false);
                deptVoList.add(orgTreeDataVo);
            }
            orgSelectShowVo.setChildDepartments(deptVoList);
        }
        if (!StrUtil.equals(type, NodeUserTypeEnum.DEPT.getKey())) {
            List<OrgDataVo> userVoList = new ArrayList();
            List<StaffDTO> userList = systemApi.getUserByDept(deptId).getData();
            for (StaffDTO user : userList) {
                OrgDataVo orgTreeDataVo = new OrgDataVo();
                orgTreeDataVo.setId(user.getId());
                orgTreeDataVo.setName(user.getDeptName());
                orgTreeDataVo.setType(NodeUserTypeEnum.USER.getKey());
                orgTreeDataVo.setSelected(false);
                orgTreeDataVo.setAvatar(user.getAvatar());
                userVoList.add(orgTreeDataVo);
            }
            orgSelectShowVo.setEmployees(userVoList);
        }
        if (StrUtil.isNotBlank(deptId)) {
            List<Dept> allDept = systemApi.getAllDept().getData();
            List<Dept> depts = DataUtil.selectParentByDept(Long.getLong(deptId), allDept);
            orgSelectShowVo.setTitleDepartments(CollUtil.reverse(depts));
        }
        return orgSelectShowVo;
    }
    /**
     * 查询所有的组织架构 并树形显示
     */
    @Override
    public List getOrgTreeDataAll(String keywords, Integer status) {
        List<Dept> deptDtoList = systemApi.getAllDept().getData();
        if (StrUtil.isNotBlank(keywords) || status != null) {
            List list = new ArrayList();
            for (Dept dept : deptDtoList) {
                String leaderIdList = dept.getLeader().toString();
                List<NodeUser> leaderUserList=new ArrayList<>();
                    StaffDTO user = systemApi.getStaffByUserId(leaderIdList).getData();
                    NodeUser nodeUser=new NodeUser();
                    nodeUser.setUserId(leaderIdList);
                    nodeUser.setName(user.getStaffName());
                    nodeUser.setType(NodeUserTypeEnum.USER.getKey());
                    nodeUser.setSelected(true);
                    nodeUser.setAvatar(user.getAvatar());
                    leaderUserList.add(nodeUser);
                Dict set = Dict.create()
                        .set("leaderUser", leaderUserList)
                        .set("id", String.valueOf(dept.getDeptId()))
                        .set("name", dept.getDeptName())
                        .set("rootIdList", CollUtil.reverse(DeptUtil.queryRootIdList(dept.getDeptId().toString(),
                                deptDtoList)));
                list.add(set);
            }
            return list;
        }

        List<TreeNode<String>> nodeList = CollUtil.newArrayList();

        for (Dept dept : deptDtoList) {



            TreeNode<String> treeNode = new TreeNode<>(String.valueOf(dept.getDeptId()), String.valueOf(dept.getParentId()),
                    dept.getDeptName(), 1);

            String leaderIdList =dept.getLeader().toString();

            List<NodeUser> leaderUserList=new ArrayList<>();

                StaffDTO user = systemApi.getStaffByUserId(leaderIdList).getData();

                NodeUser nodeUser=new NodeUser();
                nodeUser.setUserId(leaderIdList);
                nodeUser.setName(user.getStaffName());
                nodeUser.setType(NodeUserTypeEnum.USER.getKey());
                nodeUser.setSelected(true);
                nodeUser.setAvatar(user.getAvatar());
                leaderUserList.add(nodeUser);

            treeNode.setExtra(Dict.create().set("leaderUser", leaderUserList)
                    .set("rootIdList", CollUtil.reverse(DeptUtil.queryRootIdList(String.valueOf(dept.getDeptId()),
                            deptDtoList)))
            );
            nodeList.add(treeNode);

        }
        // 0表示最顶层的id是0
        return TreeUtil.build(nodeList, "0");
    }


    /**
     * 模糊搜索用户
     */
    @Override
    public List<OrgDataVo> getOrgTreeUser(String userName) {

        List<StaffDTO> userList = systemApi.searchStaff(userName).getData();

        List<OrgDataVo> orgTreeDataVoList = new ArrayList<>();

        for (StaffDTO user : userList) {
            OrgDataVo orgTreeDataVo = new OrgDataVo();
            orgTreeDataVo.setId(user.getId());
            orgTreeDataVo.setName(user.getStaffName());
            orgTreeDataVo.setType(NodeUserTypeEnum.USER.getKey());
            orgTreeDataVo.setAvatar(user.getAvatar());
            orgTreeDataVoList.add(orgTreeDataVo);

        }

        return orgTreeDataVoList;
    }


    /**
     * 获取用户信息
     */
    @Override
    public StaffDTO getUserDetail(String userId) {
        return systemApi.getStaffByUserId(userId).getData();
    }
}
